PROGRAM MAIN
  USE GLOBVAR
  USE INIT
  USE DATAMM 
  USE smm
  !USE smm2
  USE NRUTIL
  USE MATRIX
  USE PROBABILITY
  USE ars 
  USE ANNEALING
  !USE weight
  USE smmboot
  !USE LIKELIHOOD
  USE RANDOM
  USE MINIMIZATION,ONLY: BFGS
  USE SIMPLEX
  USE STATISTICS
  USE boots
  
  !USE MPI
  
IMPLICIT NONE
  REAL(8) :: theta(N_var),bound(N_var,2),theta_initial(N_var)
  REAL(8) :: mu,sig,aa,mm(n_mom),aa2,momm(n_boot,n_mom)!,winv(n_mom2,n_mom2)
  LOGICAL :: check

  
  INTEGER :: j,n,ierr,hz,tin,tout,k,i,jj,kk
  myid=0

  CALL INITIALIZE()
  CALL datam(mm)
  moment=mm
   OPEN(6424,file="data.out")
    DO i = 1,N_mom 
      WRITE(6424,'(200F16.8)') moment(i)
    END DO
   CLOSE(6424)
   !stop
  theta=0.0d0
  !kk=n_x_l0+3*N_levelc+n_x_eta+2
  !theta(kk+1:n_var)=0.0d0
  !theta(kk+n_levelc+1)=1.0d0

                OPEN(1,file="initial.out")
                    DO j=1,SIZE(thetafix)
                       READ(1,fmt=*) thetafix(j)
                    END DO
                CLOSE(1)


                OPEN(1,file="initialpoint.out")
                    DO j=1,SIZE(theta)
                       READ(1,fmt=*) theta_initial(j)
                    END DO
                CLOSE(1)
        theta=theta_initial
        aa=mom(theta)
        !aa2=mom2(theta)
        !theta=theta_true!*0.90d0
       IF (myid==0) write(*,*) aa,aa2
              !stop
      CALL BOOT(momm)
      momentboot=momm
      !call coun(theta,counter)
      
      DO i=1,n_boot
          moment(:)=momentboot(i,:)
          mmb(:)=mmboot(i,:)
          theta=theta_initial
          DO j=1,n_var
            if (j<=n_var-2 .and. j>n_var-12) theta(j)=SAMPLE_UNIFORM(theta_initial(j)-0.02,theta_initial(j)+0.02)
            if (j>n_var-2) theta(j)=SAMPLE_UNIFORM(theta_initial(j)-0.00002,theta_initial(j)+0.00002)

          END DO

          CALL bfgs(theta,1.0d-4,1.0d-5,momb,0,.False.) 
          CALL Nelder_Meade(theta,1.0d-8,momb,0,2000)
          CALL Nelder_Meade(theta,1.0d-8,momb,0,2000)
          CALL Nelder_Meade(theta,1.0d-8,momb,0,2000)
          CALL Nelder_Meade(theta,1.0d-8,momb,0,2000)
          thetaboot(i,:)=theta(:)
                    write(*,*) i

           OPEN(12,file="thetaboot.out")
             DO k=1,N_var
              WRITE(12,'(2000F32.12)') (thetaboot(j,k),j=1,i)
             END DO
           CLOSE(12) 

      END DO
      
           OPEN(12,file="thetaboot.out")
             DO i=1,N_var
              WRITE(12,'(2000F32.12)') (thetaboot(j,i),j=1,n_boot)
             END DO
           CLOSE(12) 



  
END PROGRAM MAIN
